<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<div><el-button type="warning" class="item-gap" size="small" :loading="exportLoading" @click="onExportExcel">导出</el-button></div>
				</div>
				<div class="flex-end-center-wrap">
					<currentTime :current-time="currentTime"></currentTime>
					<jk-search-input v-model="searchParams.machineName" placeholder="设备名称" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @change="onSearchBtn" @keyup.enter.native="onSearchBtn" />
					<jk-search-button class="" @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>
		<jk-card>
			<jk-table border :data="tableData" :cell-style="cellStyle" :height="tableHeight + 20" :loading="tableLoading">
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template #header>
						<div v-if="item.keyName === '切纱10km'">
							<el-popover placement="bottom" width="260">
								<div class="bottom-value">
									<div style="width: 35%">字段名：</div><el-input v-model="restrictData.code" size="mini" class="width-value" disabled></el-input>
								</div>
								<div class="bottom-value">
									<div style="width: 35%">上限值：</div><el-input v-model="restrictData.value" size="mini" class="width-value"></el-input>
								</div>
								<div class="bottom-value">
									<div style="width: 35%">下限值：</div><el-input v-model="restrictData.values" size="mini" class="width-value"></el-input>
								</div>
								<div class="bottom-value">
									<el-button size="mini" type="primary" style="margin-left: 1px; width: 100%" @click="addDataConfig">确定</el-button>
								</div>
								<div slot="reference" class="drag-info-icon" @click="quantitativeValue(item)">{{ item.title }} <span style="color: #2d8cf0;font-size: 13px;" class="el-icon-edit"></span></div>
							</el-popover>
						</div>
						<span v-else>{{ item.title }}</span>
					</template>
				</vxe-column>
			</jk-table>
			<!-- 分页组件 -->
			<!-- <footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="searchParams.count"
					@on-change="onPage"
				/>
			</footer> -->
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { formatDate, formatTime, pageConfig } from '/src/utils/jk/jk-tool';
    import permissionMixin from '../../../mixins/permission-mixin';
    import { getInfo } from '../../../api/login';
    import listView from './components/list-view';
    import chartView from './components/chart-view';
    // import scheduleShift from '../scheduleShiftProductionReport/scheduleShift';
    import {
        zlDataShiftRecord,
        iotCollectDataCountExportExcel
    } from '../../../api/production/declineProductionMonitoring';
    import { systemUserColumnConfigGet } from '@/api/system/column-config';
    import currentTime from './components/current-time';
    import data from './data.json';
    import {
        systemDataConfigCreate,
        systemDataConfigPage,
        systemDataConfigUpdate
    } from '../../../api/basicData/dataConfig';
    export default {
        name: 'DeclineProductionMonitoring',
        mixins: [permissionMixin, calHeight],
        components: {
            listView,
            chartView,
            currentTime
        },
        data() {
            return {
                prefix: '',
                viewType: 'listView',
                // processList: [],
                workshopList: [],
                visible: false,
                tableColumnList: [],
                dataId: null,
                tableLoading: false,
                exportLoading: false,
                tableData: [],
                restrictData: {
                    'auditState': 1,
                    'code': '',
                    'name': '上限值',
                    'remark': '',
                    'type': 1,
                    'value': 0,
                    'values': 0
                },
                resDateValue: 0,
                resDateValues: 0,
                searchParams: {
                    count: 0,
                    // pageNo: pageConfig.pageNo,
                    // pageSize: pageConfig.pageSize,
                    machineName: null
                    // processCode: '',
                    // belongDate: '',
                    // groupId: 1
                    // workshopId: null
                },
                currentTime: '',
                interVal2: {},
                interVal: {},
                ids: 0
            };
        },
        methods: {
            cellStyle({ row, column }) {
                const 切纱10km = Number(row.切纱10km);
                if (column.field === '切纱10km') {
                    if (切纱10km === 0) {
                        return {
                            backgroundColor: ''
                        };
                    } else if (row.切纱10km >= this.resDateValue || row.切纱10km <= this.resDateValues) {
                        if (this.resDateValue !== 0 || this.resDateValues !== 0) {
                            return {
                                backgroundColor: '#ed4014',
                                color: '#ffffff'
                            };
                        } else {
                            return {
                                backgroundColor: ''
                            };
                        }
                    } else {
                        return {
                            backgroundColor: ''
                        };
                    }
                }
            },
            // 上限
            addDataConfig() {
                this.addDataConfigDown();
                const params = JSON.parse(JSON.stringify(this.restrictData));
                params.code = this.restrictData.code + '上限';
                params.id = this.ids;
                const api = this.ids ? systemDataConfigUpdate : systemDataConfigCreate;
                return api(params).then(res => {
                    if (res.data.status === 200) {
                        this.getUpConfigPage();
                        this.getListRequest();
                        document.body.click();
                        this.$tipsBar(this, 'save');
                    }
                });
            },
            // 下限
            addDataConfigDown() {
                const params = JSON.parse(JSON.stringify(this.restrictData));
                params.value = params.values;
                params.code = this.restrictData.code + '下限';
                delete params.values;
                params.id = this.idss;
                const api = this.idss ? systemDataConfigUpdate : systemDataConfigCreate;
                return api(params).then(res => {
                    if (res.data.status === 200) {
                        // this.getDownConfigPage();
                        // this.getListRequest();
                        // this.$tipsBar(this, 'save');
                    }
                });
            },
            quantitativeValue(column) {
                this.$set(this.restrictData, 'code', column.keyName);
                this.$set(this.restrictData, 'name', column.keyName);
            },
            getUpConfigPage() {
                this.tableLoading = true;
                const params = {
                    pageNo: 1,
                    pageSize: 100,
                    code: '切纱10km上限'
                };
                return systemDataConfigPage(params).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.$set(this.restrictData, 'value', res.data.res.length > 0 ? Number(res.data.res[0].value) : 0);
                        this.resDateValue = res.data.res.length > 0 ? Number(res.data.res[0].value) : 0;
                        this.ids = res.data.res.length > 0 ? Number(res.data.res[0].id) : 0;
                    } else {
                        this.$set(this.restrictData, 'value', res.data.res.length > 0 ? Number(res.data.res[0].value) : 0);
                        this.resDateValue = res.data.res.length > 0 ? Number(res.data.res[0].value) : 0;
                        this.ids = res.data.res.length > 0 ? Number(res.data.res[0].id) : 0;
                    }
                });
            },
            getDownConfigPage() {
                this.tableLoading = true;
                const params = {
                    pageNo: 1,
                    pageSize: 100,
                    code: '切纱10km下限'
                };
                return systemDataConfigPage(params).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.$set(this.restrictData, 'values', res.data.res.length > 0 ? Number(res.data.res[0].value) : 0);
                        this.resDateValues = res.data.res.length > 0 ? Number(res.data.res[0].value) : 0;
                        this.idss = res.data.res.length > 0 ? Number(res.data.res[0].id) : 0;
                    } else {
                        this.$set(this.restrictData, 'values', res.data.res.length > 0 ? Number(res.data.res[0].value) : 0);
                        this.resDateValues = res.data.res.length > 0 ? Number(res.data.res[0].value) : 0;
                        this.idss = res.data.res.length > 0 ? Number(res.data.res[0].id) : 0;
                    }
                });
            },
            getMenuColumnListRequest() {
                return systemUserColumnConfigGet({ path: 'DeclineProductionMonitoring', filterShow: true }).then(res => {
                    if (res.data.status === 200) {
                        this.tableColumnList = res.data.res.columnConfigList && res.data.res.columnConfigList.length ? res.data.res.columnConfigList[0].itemList : [];
                    }
                });
            },
            getUserInfoRequest() {
                return getInfo().then(res => {
                    if (res.data.status === 200) {
                        this.workshopList = res.data.res.workshop.workshops;
                        this.getListRequest();
                    }
                });
            },
            runTime() {
                this.yearMonthDay = formatTime(Date.now()).slice(0, 10);
                this.hourMinuteSecond = formatTime(Date.now()).slice(-9);
                this.currentTime = formatTime(Date.now());
                clearInterval(this.interVal2);
                this.interVal2 = setInterval(() => {
                    this.currentTime = formatTime(Date.now());
                }, 1000);
            },
            runData() {
                this.getListRequest();
                clearInterval(this.interVal);
                this.interVal = setInterval(() => {
                    this.getListRequest();
                }, 10000);
            },
            clearTimer() {
                clearInterval(this.interVal);
                clearInterval(this.interVal2);
            },
            /** 查询列表 */
            getListRequest() {
                // 页面加载loading
                // this.tableLoading = true;
                zlDataShiftRecord(this.searchParams).then(res => {
                    // this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.tableData.forEach(x => {
                            if (x.单锭效率) {
                                x.单锭效率 = `${x.单锭效率}%`;
                            }
                        });
                        this.searchParams.count = res.data.count;
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                // this.searchParams.pageNo = 1;
                // this.searchParams.count = 1;
                this.getListRequest();
            },
            /** 导出按钮操作 */
            onExportExcel() {
                this.exportLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                params.pageNo = 1;
                params.pageSize = 500;
                this.$modal.confirm('是否确认导出所有数据数据项?').then(() => {
                    this.exportLoading = true;
                    return zlDataShiftRecord(params);
                }).then(res => {
                    if (res.data.status === 200) {
                import('@/vendor/Export2Excel').then(excel => {
                  const tHeader = this.tableColumnList.map(x => x.title);
                  const filterVal = this.tableColumnList.map(x => x.keyName);
                  const list = res.data.res ? res.data.res : [];
                  // 保留一位小数设备名称
                  const arr = ['单锭效率', '切纱10km'];
                  const minification = ['纱疵'];
                  const arrName = ['纱疵', '纱线接头(捻接)', '自然纱线断头', '很短的粗节', '短粗节/或标准差', '长粗节', '细节', '启动期间纱支疵点数的公差上限', '启动期间纱支疵点数的公差下限', '运行期间纱支偏差的公差上限', '运行期间纱支疵点数的公差下限', 'D+ [/100km]', 'D- [/100km]', 'CD+ [/100km]', 'CD- [/100km]', '周期性瑕疵点', '深色异纤(浅色纱线中的深色纤维)', '纱线接头的公差上限', '纱线接头的公差下限', 'swNSL [/100km]', 'swT [/100km]'];
                  list.forEach((obj) => {
                    Object.keys(obj).forEach((key) => {
                      arr.forEach(y => {
                        if (key === y) {
                          obj[key] = this.getOneFloat(obj[key]);
                        }
                      });
                      arrName.forEach(x => {
                        if (key === x) {
                          obj[key] = Math.ceil(obj[key]);
                        }
                      });
                      minification.forEach(x => {
                        if (key === x) {
                          obj[key] = this.minification(obj[key]);
                        }
                      });
                    });
                  });
                  const data = this.formatJson(filterVal, list);
                  excel.export_json_to_excel({
                    header: tHeader,
                    data,
                    filename: `${this.$route.meta.title}(${formatDate(Date.now())})`,
                    autoWidth: true,
                    bookType: 'xlsx'
                  });
                });
                    }
                    this.exportLoading = false;
                });
            },
            // Math.ceil(number);
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                    return v[j];
                }));
            },
            minification(num) {
                const numMain = Number(num);
                return numMain / 100;
            },
            getOneFloat(num) {
                const numMain = Number(num);
                return parseFloat(numMain.toFixed(1));
            },
            async getDependentData() {
                // this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                // this.processList = this.$store.state.user.userProcess.processList;
                // this.$set(this.searchParams, 'belongDate', formatDate(Date.now()));
                // this.getCurrentTimeScheduleShift();
                this.getUpConfigPage();
                this.getDownConfigPage();
                await this.getUserInfoRequest();
                await this.getMenuColumnListRequest();
                this.getListRequest();
            }
        },
        beforeRouteEnter(to, from, next) {
            next((_this) => {
                _this.runTime();
                _this.runData();
            });
        },
        beforeRouteLeave(to, from, next) {
            this.clearTimer();
            next();
        },
        mounted() {
            this.getDependentData();
        }
    };
</script>
<style scoped>
.bottom-value{
  display: flex;
  align-items: center;
  margin-bottom: 2px;
  width: 100%;
}
.width-value{
  width: 65%;
}
</style>
